package com.demo2do.fms.admin.web.controller.authority.user;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.fms.admin.service.DataService;
import com.demo2do.fms.admin.service.authority.ResourceService;
import com.demo2do.fms.admin.service.authority.RoleService;
import com.demo2do.fms.admin.service.authority.UserService;
import com.demo2do.fms.admin.service.supplier.SupplierService;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.entity.authority.Branch;
import com.demo2do.fms.entity.authority.Resource;
import com.demo2do.fms.entity.authority.Role;
import com.demo2do.fms.entity.authority.RoleTemplate;
import com.demo2do.fms.entity.authority.User;
import com.demo2do.fms.entity.supplier.common.Supplier;

/**
 * 分区用户管理
 * 
 * @author Ysy
 *
 */
@Controller
@RequestMapping("/branch-users")
@MenuSetting("menu-authority")
public class BranchUserController {
    
    private static final Logger logger = LoggerFactory.getLogger(BranchUserController.class);
    
    private static final RoleTemplate[] BRANCH_USER_ROLE_TEMPLATE = {RoleTemplate.BRANCH_USER};
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private ResourceService resourceService;
    
    @Autowired
    private SupplierService supplierService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Branch> branchService;

    /**
     * list all branch_users
     * 
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-branch-user-management")
    public ModelAndView list(Page page){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/branch/branch-user-list");
        
        int totals = userService.count(BRANCH_USER_ROLE_TEMPLATE);
        if(totals > 0){
            
            List<User> users = userService.list(BRANCH_USER_ROLE_TEMPLATE, page.with(totals));
            
            modelAndView.addObject("users", users);
            modelAndView.addObject("page", page);
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * display create panel
     * 
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    @MenuSetting("submenu-branch-user-management")
    public ModelAndView create(){
        ModelAndView modelAndView = new ModelAndView("authority/user/branch/branch-user-create");
        
        RoleTemplate roleTemplate = RoleTemplate.BRANCH_USER;
        
        // find roles according to the role template
        List<Role> roles = roleService.list(Arrays.asList(roleTemplate));
        
        //list all branch
        List<Branch> branches = branchService.listAll(Branch.class);
        
        modelAndView.addObject("roles", roles);
        modelAndView.addObject("branches", branches);
        
        return modelAndView;
        
    }
    
    
    /**
     * on create
     * 
     * @param operator
     * @param user
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @MenuSetting("submenu-branch-user-management")
    public @ResponseBody HttpResult onCreate(@Secure(property = "id") Long operator,
                                             User user){
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            userService.createBranchUser(user, operator);
            
            httpResult.success().message("创建分区用户成功！");
            
        } catch (Exception e) {
            httpResult.fail("500").message("创建分区用户失败! " + e.getMessage());
            logger.error("#onCreate() - create branch user fail, exception is [{}]", e);
        }
        
        return httpResult;
    }
    
    
    /**
     * display edit panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id){
        ModelAndView modelAndView = new ModelAndView("authority/user/branch/branch-user-edit");
        
        User user = userService.load(User.class, id);
        
        modelAndView.addObject("user", user);
        return modelAndView;
    }
    
    /**
     * on edit
     * 
     * @param user
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEdit(@Preloading("userId") User user, @Secure(property = "id") Long operator){
        
        HttpResult httpResult = new HttpResult();
        
        userService.editAdminOrBranch(user, operator);
        
        httpResult.success().message("修改用户成功！");
        
        return httpResult;
        
    }
    
    /**
     * display delete panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable("id") Long id){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/branch/branch-user-delete");
        
        modelAndView.addObject("id", id);
        
        return modelAndView;
        
    }
    
    /**
     * on delete
     * 
     * @param user
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onDelete(@Preloading("userId") User user,
                                             @Secure(property = "id") Long operator) {
        
        HttpResult httpResult = new HttpResult();
        
        userService.deleteAdminOrBranch(user, operator);
        
        httpResult.success().message("删除用户成功！");
        
        return httpResult;
    }
    
    /**
     * display reset password panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.GET)
    public ModelAndView resetPassword(@PathVariable("id") Long id){
        ModelAndView modelAndView = new ModelAndView("authority/user/branch/branch-user-reset-password");
        
        modelAndView.addObject("id", id);
        return modelAndView;
    }
    
    /**
     * on reset password
     * 
     * @param user
     * @param password
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onResetPassword(@Preloading("userId") User user,
                                                    @RequestParam("password") String password,
                                                    @Secure(property = "id") Long operator){
        
        HttpResult httpResult = new HttpResult();
        
        userService.resetPassword(user, password, operator);
        
        httpResult.success()
                  .message("重置密码成功！");
        
        return httpResult;
    }
    
    /**
     * view
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @MenuSetting("submenu-branch-user-management")
    public ModelAndView view(@PathVariable("id") Long id){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/branch/branch-user-view");
        
        User user = userService.load(User.class, id);
        
        modelAndView.addObject("user", user);
        return modelAndView;
    }
    
    /**
     * view resource（菜单权限）
     * 
     * @param id
     * @param page
     * @return
     */
    @RequestMapping(value = "/{id}/resources", method = RequestMethod.GET)
    @MenuSetting("submenu-branch-user-management")
    public ModelAndView viewResource(@PathVariable("id") Long id, Page page){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/branch/branch-user-resource-view");
        
        // 1. load user by id
        User user = userService.load(User.class, id);
        
        // 2. count resource by user
        int totals = resourceService.count(user);
        
        if(totals > 0){
          // 3. load resources by user
            List<Resource> resources = resourceService.list(user, page.with(totals));
            
            modelAndView.addObject("resources", resources);
            modelAndView.addObject("page", page);
        }
        
        modelAndView.addObject("user", user);
        modelAndView.addObject("totals", totals);
        
        return modelAndView;
    }
    
    /**
     * view supplier（供应商管辖权限）
     * 
     * @param id
     * @param page
     * @return
     */
    @RequestMapping(value = "/{id}/suppliers", method = RequestMethod.GET)
    @MenuSetting("submenu-branch-user-management")
    public ModelAndView viewSupplier(@PathVariable("id") Long id, Page page){
        
        ModelAndView modelAndView = new ModelAndView("authority/user/branch/branch-user-supplier-view");
        
        // 1. load user by id
        User user = userService.load(User.class, id);
        
        // 2. count suppliers by user
        int totals = supplierService.count(Supplier.class);
        
        if(totals > 0){
            
            // 3. list suppliers by user and page
            List<Supplier> suppliers = supplierService.listByPage(Supplier.class, page.with(totals));
            
            modelAndView.addObject("suppliers", suppliers);
            modelAndView.addObject("page", page);
        }
        
        modelAndView.addObject("totals", totals);
        modelAndView.addObject("user", user);
        
        return modelAndView;
    }
    
    /**
     * 同步到VAM
     * @return
     */
    @RequestMapping(value = "/{id}/sync-vam", method = RequestMethod.GET)
    @MenuSetting("submenu-admin-user-management")
    public ModelAndView syncVam(@PathVariable("id") Long userId) {
    	
    	ModelAndView modelAndView = new ModelAndView("authority/user/branch/branch-user-sync-vam");
    	
    	User user = userService.load(User.class, userId);
    	
    	modelAndView.addObject("user", user);
    	
    	return modelAndView;
    }
    
    @RequestMapping(value = "/{id}/sync-vam", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @MenuSetting("submenu-admin-user-management")
    public @ResponseBody HttpResult onSyncVam(@Preloading("userId") User user, @Secure(property = "id") Long operator) {
    	
    	HttpResult httpResult = new HttpResult();
        try {
			userService.editAdminOrBranch(user, operator);
			
            httpResult.success().message("同步至VAM成功！");

		} catch (Exception e) {
			
			httpResult.fail("500").message("同步至VAM失败! " + e.getMessage());
			
			logger.error("#onSysncVam() - sysnc user information to vam fail, exception is [{}]", e);
		}
        return httpResult;
    }
    
    
}
